<?php

namespace app\core\services\user;

use app\core\access\Rbac;
use app\core\entities\User;
use app\core\repositories\user\UserRepository;
use app\core\services\RoleManager;
use app\core\services\TransactionManager;
use DomainException;
use yii\base\Exception;

class SignupService
{
    private UserRepository $users;
    private RoleManager $roles;
    private TransactionManager $transaction;

    public function __construct(
        UserRepository $users,
        RoleManager $roles,
        TransactionManager $transaction
    )
    {
        $this->users = $users;
        $this->roles = $roles;
        $this->transaction = $transaction;
    }

    /**
     * @throws Exception
     * @throws \yii\db\Exception
     */
    public function smartSignup($form): User
    {
        $user = User::requestSmartSignup($form->email);
        $this->transaction->wrap(function () use ($user) {
            $this->users->save($user);
            $this->roles->assign($user->id, Rbac::ROLE_USER);
        });
        return $user;
    }

    public function confirm($token): void
    {
        if (empty($token)) {
            throw new DomainException('Empty confirm token.');
        }
        $user = $this->users->getByEmailConfirmToken($token);
        $user->confirmSignup();
        $this->users->save($user);
    }
}
